package org.android.kumoh_ing;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;


import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.facebook.android.FacebookError;
import com.facebook.android.Util;

public class HomeActivity extends Activity {
	private Button mBtnWrite,mBtnCheck;
	private Button mapview;
	private Button group_cal, setting ;
	private EditText mInText;
	private TextView myName;
	private String name;
	private String group_id;
	private String resStr = "";
	private ArrayList<String> groupfeeds;
	private TextView groupfeed;
//	private String loc ="";
	private ViewSwitcher switcher;
	private OtherDBTransfer otherTransfer ;
	private LocationDBTransfer locDBTrans ;
	int index;
//	FileOutputStream fos;
//	FileInputStream fis;

	Animation startanim ;
	
	FeedListView feedList;
	FeedListAdapter2 feedAdapter;
	Handler feedhandler;
	Handler getuserhandler;
	groupfeedThread thread;
	thread_getUser getUserThread;
	
	private int count;//,curCount;
	String Phone;
	String[][] change;
	String MY_id="";
	int memCount;

	// private ArrayList<FeedItem> mItems = new ArrayList<FeedItem>();
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
	//	initChange();	//최신 업로드된 정보 파일에 쓸수 있도록 이차원 배열 사용
		initSetting();
		
		feedList.setAdapter(feedAdapter);
		feedList.setOnDataSelectionListener(new OnDataSelectionListener() {

			public void onDataSelected(AdapterView parent, View v, int position, long id) {
				FeedItem curItem = (FeedItem) feedAdapter.getItem(position);
				//File Userinfo = getDir("Userinfo5", Activity.MODE_PRIVATE); // 파일에서 읽기 
				String curId = curItem.getId();
				try {
					Phone=otherTransfer.getPhoneFromID(curId);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				/*
				String path = Userinfo.getAbsolutePath();
				File uInfo = new File(path + "/" + group_id + ".txt");
				try {

					fis = new FileInputStream(uInfo);
					byte[] data = new byte[fis.available()];
					while (fis.read(data) != -1) {
						;
					}// -1 전체 다읽은거
					fis.close();

					resStr = new String(data);// String으로 바꿔서 출력해야함. String생성자

				} catch (FileNotFoundException e) {

				} catch (IOException e) {

					// TODO Auto-generated catch block
  
				}
				
				String curId = curItem.getId();

				StringTokenizer res = new StringTokenizer(resStr, "//");
				while (res.hasMoreTokens()) {
					String curStr = res.nextToken();
					StringTokenizer _id = new StringTokenizer(curStr, "$");
					String User_Id = _id.nextToken();
					if (User_Id.equalsIgnoreCase(curId)) {
						Phone = _id.nextToken();
						break;
					}   

				}*/
				if(Phone != null){
					choiceItemDialog();
				}
			}
		});

		mBtnEvent();
		mBtnCheck.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						GroupTextActivity.class);
				intent.putExtra("group_id", group_id);
				startActivity(intent);
			}
		});
		
		group_cal.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					if(count == otherTransfer.getGroupMemberCount(group_id)){
						Intent intent = new Intent(getBaseContext(), CalendarMonthViewActivity.class);
						intent.putExtra("groupname", name);
						intent.putExtra("group_id", group_id);
						intent.putExtra("m_count", count);
						startActivity(intent);
					}
					else{
						Toast.makeText(getApplicationContext(), "groupID="+group_id, Toast.LENGTH_LONG).show();
						Toast.makeText(getApplicationContext(), "count="+count+"  DBcount ="+otherTransfer.getGroupMemberCount(group_id), Toast.LENGTH_LONG).show();
						Toast.makeText(getApplicationContext(), "그룹 구성원의 정보부족", Toast.LENGTH_LONG).show();
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}
	/*
	private void initChange(){
		Bundle para = new Bundle();
		String responseStr;
		
		try {
			responseStr = facebookvalue.FacebookInstance.request(group_id + "/members", para);
			JSONObject resultObj = Util.parseJson(responseStr);
			JSONArray jArray = resultObj.getJSONArray("data");
			memCount=jArray.length();
			change = new String[memCount][2];		
			
			for (int i = 0; i < memCount; i++) {
				JSONObject obj = jArray.getJSONObject(i);
				String id = obj.getString("id");
				change[i][0]=id;
				change[i][1]="O";
			}
			
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FacebookError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		
	}
	*/
	private void choiceItemDialog() {

		final CharSequence[] items = { "메세지 전송", "전화 걸기" };

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);

		// alt_bld.setIcon(R.drawable.icon);
		alt_bld.setTitle("Select Connection type");
		alt_bld.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int item) {
				// TODO Auto-generated method stub
				switch (item) {
				case 0:
					Intent intent0 = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Phone));
					startActivity(intent0);
					break;
				case 1:
					Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + Phone));
					startActivity(intent1);
					break;
				}
			}
		});

		AlertDialog alert = alt_bld.create();
		alert.show();
	}

	
	
	private void initSetting() {
		feedhandler = new Handler();
		getuserhandler = new Handler();
		feedAdapter = new FeedListAdapter2(this);
		groupfeeds = new ArrayList<String>();
		mBtnWrite = (Button) findViewById(R.id.button2);
		mInText = (EditText) findViewById(R.id.editText1);
		mapview = (Button) findViewById(R.id.btnLocation);
		myName = (TextView) findViewById(R.id.textView6);
		groupfeed = (TextView) findViewById(R.id.groupfeed);
		feedList = (FeedListView) findViewById(R.id.feedList);
		mBtnCheck = (Button)findViewById(R.id.btnCheck);
		setting = (Button) findViewById(R.id.button3);
		switcher = (ViewSwitcher) findViewById(R.id.viewswither);
		thread = new groupfeedThread();
		getUserThread = new thread_getUser();
		group_cal = (Button) findViewById(R.id.group_cal);
		startanim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.startalpha);
		otherTransfer = new OtherDBTransfer();
		groupfeeds.clear();
		group_id = getIntent().getExtras().getString("group_id");
		MY_id = getIntent().getExtras().getString("my_id");
		locDBTrans = new LocationDBTransfer();
		try {
			String responseStr = facebookvalue.FacebookInstance.request(group_id);
			JSONObject resultObj = Util.parseJson(responseStr);
			name = resultObj.getString("name");
			String curPicture = null;
			curPicture = resultObj.getString("icon");
 
			ImageView image = (ImageView) findViewById(R.id.imageView4);

			Bitmap curBitmap = BitmapFactory.decodeStream(new URL(curPicture)
					.openStream());

			image.setMaxHeight(30);
			image.setMaxWidth(30);
			image.setMinimumHeight(30);
			image.setMinimumWidth(30);

			image.setImageBitmap(curBitmap);

		} catch (Exception ex) {
			ex.printStackTrace();
		} catch (FacebookError ext) {
			ext.printStackTrace();
		}
		myName.setText(name);
		getUserThread.start();
		//thread.start();

	}

	private void mBtnEvent() {

		mapview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						SharedLocationActivity.class);
				intent.putExtra("group_id", group_id);
				intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				startActivity(intent);

			}
		});
		
		mBtnWrite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String statusText = mInText.getText().toString();
				if (statusText.length() < 1) {
					Toast.makeText(getApplicationContext(), "입력 하세요.", 1000).show();
					return;
				}
				try {
					updateStatus(statusText);
				} catch (FacebookError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		setting.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent settingintent = new Intent(getApplicationContext(),
						SettingActivity.class);
				settingintent.putExtra("my_id", MY_id);
				startActivity(settingintent);
			}
		});
	}

	private void updateStatus(String statusText) throws FacebookError {
		//startLocationService();
		try {
			String jstr;
			Bundle params = new Bundle();
			params.putString("message", StartActivity.loc +statusText);
			params.putString("link", "");
			params.putString("description", "We Azit");

			jstr = facebookvalue.FacebookInstance.request(group_id + "/feed", params,"POST");
			JSONObject resultObj = Util.parseJson(jstr);
			String feedId = resultObj.getString("id");
			if(locDBTrans.getPermission(MY_id).equalsIgnoreCase("o")){
				locDBTrans.setFeedLocation(feedId, StartActivity.latitude.toString(), StartActivity.longitude.toString());
			}
			mInText.setText("");
			Toast.makeText(getApplicationContext(), statusText + " 전송",	1000).show();
			

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
/*
	private void startLocationService() {
		Log.d("userloca", "11111");
    	// get manager instance
    	LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	 
    	Criteria criteria = new Criteria(); 
    	criteria.setAccuracy(Criteria.ACCURACY_FINE);
    	criteria.setAltitudeRequired(false);
    	criteria.setBearingRequired(false);
    	criteria.setCostAllowed(true);
    	criteria.setPowerRequirement(Criteria.POWER_LOW);
    	String provider = manager.getBestProvider(criteria,true);
    	

    	// set listener
    	GPSListener gpsListener = new GPSListener();
		long minTime = 0;
		float minDistance = 20;

		manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,minTime,minDistance,gpsListener);
		
		// in case of network provider
		manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,minTime,minDistance,gpsListener);

		// get last known location first
		try {
			Location lastLocation = manager.getLastKnownLocation(provider);
			Log.d("userloca", "2222");
			if (lastLocation != null) {
				Log.d("userloca", "3333");
				Double latitude = lastLocation.getLatitude();
				Double longitude = lastLocation.getLongitude();
				
				// new GeoPoint to be placed on the MapView
				Log.d("userloca", "222");
				loc = "#%UserLocation="+ latitude + "$"+ longitude+"//";
				//transfer.setLocation(m_id, latitude.toString(), longitude.toString());
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		}
    }


	private class GPSListener implements LocationListener {

	    public void onLocationChanged(Location location) {
			//capture location data sent by current provider
			Double latitude = location.getLatitude();
			Double longitude = location.getLongitude();
			loc = "#%UserLocation="+ latitude + "$"+ longitude+"//";
		}
	    

	    public void onProviderDisabled(String provider) {
	    }

	    public void onProviderEnabled(String provider) {
	    }

	    public void onStatusChanged(String provider, int status, Bundle extras) {
	    }

	}
*/
	
	class groupfeedThread extends Thread {
		public void run() {
			try {
				String responseStr = facebookvalue.FacebookInstance.request(group_id + "/feed");
				JSONObject resultObj = Util.parseJson(responseStr);
				JSONArray jArray = resultObj.getJSONArray("data");
							
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject obj = jArray.getJSONObject(i);
					String curMessage = obj.getString("message");
					
					if (curMessage.length() < 12) {
						groupfeeds.add(curMessage);
					}
					else if (curMessage.substring(0, 12).equalsIgnoreCase("#%UserInfor=") == false) {
//						StringTokenizer st = new StringTokenizer(curMessage, "//");
//						while (st.hasMoreTokens()) { // 3
//
//							st.nextToken();
//							curMessage = st.nextToken(); 
//						
//						}
						groupfeeds.add(curMessage);
					}
					else{ 
//						File Userinfo = getDir("Userinfo5", Activity.MODE_PRIVATE); // 파일 에서 읽기
//						String path = Userinfo.getAbsolutePath();
//						File uInfo = new File(path + "/" + group_id+ ".txt");
//			
//						fis = new FileInputStream(uInfo);
//						
//						byte[] data = new byte[fis.available()];
//						while (fis.read(data) != -1) {
//						}// -1 전체 다읽은거
//						fis.close();
//						resStr = new String(data);// String으로 바꿔서 출력해야함. String생성자
//						String Exchange = curMessage.replaceAll("#%UserInfor=",""); //facebook
//						StringTokenizer res = new StringTokenizer(resStr, "//");    //file
//						StringTokenizer resFace = new StringTokenizer(Exchange, "$");    //facebook
//						String strFace = resFace.nextToken();	//facebook의 id
//						String test,testId;
//						String store="";
//						for(int k=0;k<memCount;k++){
//							if(change[k][0].equalsIgnoreCase(strFace))
//								index=k;	
//						}
//						
//						while (res.hasMoreTokens()) {
//							String curStr = res.nextToken();
//							test = curStr+"//";
//							StringTokenizer subres = new StringTokenizer(curStr, "$");   
//							testId = subres.nextToken(); //file의 id
//							if (test.equalsIgnoreCase(Exchange)) {
//								change[index][1]="X";
//								break;
//							}
//							else{
//								if(testId.equalsIgnoreCase(strFace)){
//									if(change[index][1].equalsIgnoreCase("O")){
//										store=resStr.replace(test,Exchange);
//										fos = new FileOutputStream(uInfo);
//										fos.write(store.getBytes());
//										fos.close();
//									}
//									change[index][1]="X";
//									break;
//								}
//								else{
//									if(res.hasMoreTokens() == false){
//										fos = new FileOutputStream(uInfo, true);
//										fos.write(Exchange.getBytes());
//										fos.close();
//										
//									}
//								}
//							}	
//						}
					}

					
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			} catch (FacebookError ext) {
				ext.printStackTrace();
			}
			
//			File Userinfo = getDir("Userinfo5", Activity.MODE_PRIVATE); // 파일에서 읽기 
//			String path = Userinfo.getAbsolutePath();
//			File uInfo = new File(path + "/" + group_id + ".txt");
//			try {
//
//				fis = new FileInputStream(uInfo);
//				byte[] data = new byte[fis.available()];
//				while (fis.read(data) != -1) {
//					;
//				}// -1 전체 다읽은거
//				fis.close();
//
//				resStr = new String(data);// String으로 바꿔서 출력해야함. String생성자
//
//			} catch (FileNotFoundException e) {
//
//			} catch (IOException e) {
//
//				// TODO Auto-generated catch block
//			}
//			curCount =0;
//			StringTokenizer res = new StringTokenizer(resStr, "//");
//			while (res.hasMoreTokens()){
//				res.nextToken();
//				curCount++;
//			}
			
			for (int i = 0; i < groupfeeds.size(); i++) {
				final int index = i;
				feedhandler.post(new Runnable() {
					public void run() {
						
						groupfeed.startAnimation(startanim);
						groupfeed.setText(groupfeeds.get(index));
					}
				});
				try {
					Thread.sleep(5900);
				} catch (Exception ex) {
				}
				if (i == groupfeeds.size() - 1) {
					i = -1;
				}
			}
		}
	}
	
	class thread_getUser extends Thread {
		public void run(){
			try {
				Bundle para = new Bundle();
				para.putString("fields", "name,picture");
				String responseStr = facebookvalue.FacebookInstance.request(group_id + "/members", para);

				feedAdapter.clear();

				JSONObject resultObj = Util.parseJson(responseStr);
				JSONArray jArray = resultObj.getJSONArray("data");
				
				for (int i = 0; i < jArray.length(); i++) {

					JSONObject obj = jArray.getJSONObject(i);
					String curName = obj.getString("name");
					String id = obj.getString("id");

					String curPicture = null; 
					try {
						curPicture = obj.getString("picture");
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					count++; // member count
					FeedItem curItem = new FeedItem(curName, curPicture, id);
					feedAdapter.addItem(curItem);
				}
				getuserhandler.post(new Runnable() {
					public void run() {
					//	feedAdapter.notifyDataSetChanged();
						feedAdapter.notifyDataSetInvalidated();
						switcher.showNext();
						thread.start();  
					}
				});
			} catch (Exception ex) {
				ex.printStackTrace();
			} catch (FacebookError ext) {
				ext.printStackTrace();
			}
		}
	}
}
